예제 #1
0
        public static async Task DemoGeoConnect()
        {
            // Make sure we prefer Japan East over North Europe
            var prefLocations = new List <string> {
                LocationNames.JapanEast                                    /*, LocationNames.NorthEurope */
            };
            DocumentClient client = await CosDB.ConnectToCosmosDB(Config.Account_GlobalBuildDemo, Config.Account_GlobalBuildDemo_Key, prefLocations);

            Database db = await CosDB.CreateOrGetDatabase(client, "demodb");

            DocumentCollection coll = await CosDB.CreateOrGetCollection(client, db, "democol", 400, null, null, false);

            Person aPerson = null;

            do
            {
                var queryable = client.CreateDocumentQuery <Person>(coll.SelfLink).Where(p => p.id == "001");
                var query     = queryable.AsDocumentQuery();
                while (query.HasMoreResults)
                {
                    var personCol = await query.ExecuteNextAsync <Person>();

                    if (personCol.Count > 0)
                    {
                        aPerson = personCol.FirstOrDefault();
                    }
                }
                await Task.Delay(1000);
            } while (aPerson == null);
        }
예제 #2
0
        public static async Task DemoTableWorkWithDocDBAPI()
        {
            DocumentClient client = await CosDB.ConnectToCosmosDB(Config.Account_DemoBuild_Table, Config.Account_DemoBuild_Table_Key);

            Database db = await CosDB.CreateOrGetDatabase(client, "TablesDB");

            DocumentCollection collection = await CosDB.CreateOrGetCollection(client, db, "person", 400, "/'$pk'", null, false);

            FeedOptions feedOptions = new FeedOptions()
            {
                PartitionKey = new PartitionKey("Hobbit")
            };

            var queryable = client.CreateDocumentQuery(collection.SelfLink, "SELECT * from p where p['FirstName']['$v'] = 'Bilbo'", feedOptions);
            // queryable = client.CreateDocumentQuery<PersonEntity>(collection.SelfLink, feedOptions).Where( doc => (doc.FirstName=="Bilbo") );
            var queryable2 = client.CreateDocumentQuery <PersonTableEntry>(collection.SelfLink, feedOptions).Where(doc => (doc.FirstName.v == "Bilbo"));

            var query2 = queryable2.AsDocumentQuery <PersonTableEntry>();

            while (query2.HasMoreResults)
            {
                var person = await query2.ExecuteNextAsync <PersonTableEntry>();
            }

            var query = queryable.AsDocumentQuery();

            while (query.HasMoreResults)
            {
                var person = await query.ExecuteNextAsync();
            }
        }
예제 #3
0
        /// <summary>
        /// Works on all consistency levels!
        /// </summary>
        /// <returns></returns>
        static async Task DemoOptimisticWrite()
        {
            try
            {
                DocumentClient client = await CosDB.ConnectToCosmosDB(Config.Account_DemoBuild_Docs, Config.Account_DemoBuild_Docs_Key);

                Database db = await CosDB.CreateOrGetDatabase(client, "demodb");

                DocumentCollection collection = await CosDB.CreateOrGetCollection(client, db, "democol", 400, null, null, false);

                var createResponse = await client.CreateDocumentAsync(collection.SelfLink, new { id = "001", name = "Book" });

                var replaceResponse = await client.ReplaceDocumentAsync(
                    createResponse.Resource.SelfLink,
                    new { id = "001", name = "Book", Title = "The Hobbit" },
                    new RequestOptions
                {
                    AccessCondition = new Microsoft.Azure.Documents.Client.AccessCondition
                    {
                        Condition = createResponse.Resource.ETag,
                        Type      = AccessConditionType.IfMatch
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"DemoOptimisticWrite failed with {ex.Message}.");
            }
        }
예제 #4
0
        /// <summary>
        /// This stores a document into CosmosDB. First the document is stored with the
        /// DocumentDB-API and then with the MongoAPI. Explore both Location-Elements:
        ///  * "LocationMongoDB" and
        ///  * "LocationCosmosDB"
        ///  and their representation in the database.
        /// </summary>
        /// <returns></returns>
        public static async Task DemoStorageOfLocation()
        {
            try
            {
                MongoItem demoDoc = new MongoItem("Hansi", "Huber", "Test", "ModeT", "",
                                                  1.1, 2.2,
                                                  new string[] { "male", "person" },
                                                  new string[] { "hansi" });
                // =======================================================
                // Store in CosmosDB
                // =======================================================
                DocumentClient docDBclient = await CosDB.ConnectToCosmosDB(Config.Account_DemoBuild_Mongo, Config.Account_DemoBuild_Mongo_Key);

                Database docDBdb = await CosDB.CreateOrGetDatabase(docDBclient, "demodb");

                DocumentCollection collection = await CosDB.CreateOrGetCollection(docDBclient, docDBdb, "democolDocDB", 400, null, null, false);

                await docDBclient.CreateDocumentAsync(collection.SelfLink, demoDoc);

                // =======================================================
                // Store with MongoDB API
                // =======================================================
                MongoQueryTest queryTest = new MongoQueryTest();
                MongoClient    client    = MongoDemo.Client;
                var            db        = client.GetDatabase("demodb");
                try
                {
                    await db.DropCollectionAsync("democol");
                }
                catch (Exception)
                {
                }
                var col = db.GetCollection <MongoItem>("democol");
                await col.InsertOneAsync(demoDoc);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"DemoMongoAPILocation Demo failed with {ex.Message}.");
                throw;
            }
        }
예제 #5
0
        static async Task DemoSessionToken()
        {
            try
            {
                DocumentClient client = await CosDB.ConnectToCosmosDB(Config.Account_DemoBuild_Docs, Config.Account_DemoBuild_Docs_Key);

                Database db = await CosDB.CreateOrGetDatabase(client, "demodb");

                DocumentCollection collection = await CosDB.CreateOrGetCollection(client, db, "democol", 400, null, null, false);

                //var queryable = client.CreateDocumentQuery(collection.SelfLink, "SELECT * FROM books WHERE books.id='001' ", new FeedOptions() { });
                var queryable = client.CreateDocumentQuery(collection.SelfLink, "SELECT * FROM books WHERE books.id='001' ", new FeedOptions()
                {
                    SessionToken = "0:16"
                });
                var query  = queryable.AsDocumentQuery();
                var result = await query.ExecuteNextAsync();

                var sessionToken = result.SessionToken;

                var createResponse = await client.CreateDocumentAsync(collection.SelfLink, new { id = "001", name = "Book" });

                var replaceResponse = await client.ReplaceDocumentAsync(
                    createResponse.Resource.SelfLink,
                    new { id = "001", name = "Book", Title = "The Hobbit" },
                    new RequestOptions
                {
                    AccessCondition = new Microsoft.Azure.Documents.Client.AccessCondition
                    {
                        Condition = createResponse.Resource.ETag,
                        Type      = AccessConditionType.IfMatch
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"DemoSessionToken failed with {ex.Message}.");
            }
        }
예제 #6
0
        public static async Task DemoGraph01()
        {
            try
            {
                DocumentClient client = await CosDB.ConnectToCosmosDB(Config.Account_DemoBuild_Hobbit, Config.Account_DemoBuild_Hobbit_Key);

                Database db = await CosDB.CreateOrGetDatabase(client, "demodb");

                DocumentCollection collection = await CosDB.CreateOrGetCollection(client, db, "thehobbit", 400, null, null, false);

                var results      = new List <dynamic>();
                var gremlinQuery = client.CreateGremlinQuery <dynamic>(collection, "g.V().hasLabel('person')");

                while (gremlinQuery.HasMoreResults)
                {
                    foreach (var result in await gremlinQuery.ExecuteNextAsync <dynamic>())
                    {
                        results.Add(result);
                    }
                }

                var typedGremlinQuery = client.CreateGremlinQuery <Vertex>(collection, "g.V().hasLabel('person')");
                while (typedGremlinQuery.HasMoreResults)
                {
                    foreach (var result in await typedGremlinQuery.ExecuteNextAsync <Vertex>())
                    {
                        Console.WriteLine(result.Label);
                        var props = result.GetVertexProperties();
                        var name  = result.GetVertexProperties("name").First().Value;
                    }
                }

                // ================================================================================
                // The following is no longer supported with 0.2.4 update
                // The classes have been updated with INTERNAL USE only
                // ================================================================================

                /*
                 * GraphConnection graphConnection = await GraphConnection.Create(Account_DemoBuild_Hobbit, Account_DemoBuild_Hobbit_Key, "demodb", "thehobbit");
                 * Microsoft.Azure.Graphs.GraphCommand cmd = new GraphCommand(graphConnection);
                 * GraphTraversal personTrav = cmd.g().V().HasLabel("person");
                 * foreach(var p in personTrav)
                 * {
                 *  Console.WriteLine(p);
                 * }
                 *
                 * Microsoft.Azure.Graphs.GraphCommand cmd2 = new GraphCommand(graphConnection, "g.V().hasLabel('person').union(V().hasLabel('place'))");
                 * var res2 = cmd2.Execute();
                 * int cnt = 0;
                 * foreach (var xx in res2)
                 * {
                 *  Console.WriteLine(xx);
                 *  cnt++;
                 * }
                 * // 105 =>  g.V().hasLabel('person').union(V().hasLabel('place'))  .count()  .limit(1)
                 */
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GraphDemo 01 failed with {ex.Message}.");
            }
        }
예제 #7
0
        private static async Task ProcessChangeFeedWithChangeFeedProcessor(DocumentClient client, Database db, DocumentCollection personCol)
        {
            // Use the ChangeFeed Processor which manages to read changes accross partitions.
            // This requires another CosmosDB collection so that ChangeFeedProcessor can store it's lease information!
            // https://docs.microsoft.com/en-us/azure/cosmos-db/change-feed#change-feed-processor
            #region Change Feed Processor
            // Create LeaseCollection
            DocumentCollection leasecol = await CosDB.CreateOrGetCollection(client, db, "leasecol", 400, null, null, false, true);

            // Customizable change feed option and host options
            ChangeFeedOptions feedOptions = new ChangeFeedOptions()
            {
                // ie customize StartFromBeginning so change feed reads from beginning
                // can customize MaxItemCount, PartitonKeyRangeId, RequestContinuation, SessionToken and StartFromBeginning
                StartFromBeginning = true
            };
            ChangeFeedHostOptions feedHostOptions = new ChangeFeedHostOptions()
            {
                // ie. customizing lease renewal interval to 15 seconds
                // can customize LeaseRenewInterval, LeaseAcquireInterval, LeaseExpirationInterval, FeedPollDelay
                LeaseRenewInterval = TimeSpan.FromSeconds(15)
            };
            string hostName = "UniqueHostName01";
            DocumentCollectionInfo documentCollectionLocation = new DocumentCollectionInfo()
            {
                CollectionName   = personCol.Id,
                ConnectionPolicy = ConnectionPolicy.Default,
                DatabaseName     = db.Id,
                MasterKey        = Config.Account_DemoBuild_Mongo_Key,
                Uri = new Uri(Config.Account_DemoBuild_Mongo)
            };
            DocumentCollectionInfo leaseCollectionLocation = new DocumentCollectionInfo()
            {
                CollectionName   = "leasecol",
                ConnectionPolicy = ConnectionPolicy.Default,
                DatabaseName     = db.Id,
                MasterKey        = Config.Account_DemoBuild_Mongo_Key,
                Uri = new Uri(Config.Account_DemoBuild_Mongo)
            };

            DocumentFeedObserverFactory docObserverFactory = new DocumentFeedObserverFactory();
            ChangeFeedEventHost         host = new ChangeFeedEventHost(hostName,
                                                                       documentCollectionLocation,
                                                                       leaseCollectionLocation,
                                                                       feedOptions, feedHostOptions);

            await host.RegisterObserverFactoryAsync(docObserverFactory);

            Console.WriteLine("Waiting 2-3 seconds before adding more documents...");
            Thread.Sleep(2500);

            Random        randGen = new Random((int)DateTime.Now.Ticks);
            List <string> cities  = new List <string>()
            {
                "Vienna", "Paris", "Frankfurt", "Prag", "Seattle"
            };
            for (int c = 0; c < 10000; c++) // with this long running sample, the Lease is probably lost
            {
                string city = cities[randGen.Next() % cities.Count];
                await client.CreateDocumentAsync(personCol.SelfLink, new Person()
                {
                    name = Guid.NewGuid().ToString("D"), city = city, label = "person"
                });

                await client.CreateDocumentAsync(personCol.SelfLink, new Person()
                {
                    name = Guid.NewGuid().ToString("D"), city = city, label = "person"
                });

                await client.CreateDocumentAsync(personCol.SelfLink, new Person()
                {
                    name = Guid.NewGuid().ToString("D"), city = city, label = "person"
                });
            }

            Console.WriteLine("Observer is still running... Modify or add documents with DocumentStudio. Press enter to stop.");
            Console.ReadLine();

            await host.UnregisterObserversAsync();

            #endregion
        }
예제 #8
0
        /// <summary>
        /// This demo shows how you can use the ChangeFeed Functionality in CosmosDB
        /// Requires Nuget package: Microsoft.Azure.DocumentDB.ChangeFeedProcessor
        /// This demo requires:
        ///     CosmosDB Account set up and configuration of
        ///         Account_DemoBuild_Mongo
        ///         Account_DemoBuild_Mongo_Key
        /// It will create a demodb-database
        ///     A partitioned personcol-Collection
        ///     A non paritioned leasecol-Collection
        /// </summary>
        /// <returns></returns>
        public static async Task DemoChangeFeed()
        {
            try
            {
                // Create a new Demo Collection "personcol" in "demodb"-Database
                Console.Write("Creating collection 'personcol' in 'demodb' (Demo_Build_Mongo Account),...");
                DocumentClient client = await CosDB.ConnectToCosmosDB(Config.Account_DemoBuild_Mongo, Config.Account_DemoBuild_Mongo_Key);

                Database db = await CosDB.CreateOrGetDatabase(client, "demodb");

                DocumentCollection personCol = await CosDB.CreateOrGetCollection(client, db, "personcol", 400, "/city", null, false, true);

                Console.WriteLine("Done");

                // Add several documents with corresponding partition keys
                Console.Write("Adding serveral 'person'-documents to personcol,...");
                await client.CreateDocumentAsync(personCol.SelfLink, new Person()
                {
                    name = "Isabelle", city = "Vienna", label = "person"
                });

                await client.CreateDocumentAsync(personCol.SelfLink, new Person()
                {
                    name = "Michaela", city = "Vienna", label = "person"
                });

                await client.CreateDocumentAsync(personCol.SelfLink, new Person()
                {
                    name = "Michelle", city = "Paris", label = "person"
                });

                await client.CreateDocumentAsync(personCol.SelfLink, new Person()
                {
                    name = "Chantelle", city = "Paris", label = "person"
                });

                await client.CreateDocumentAsync(personCol.SelfLink, new Person()
                {
                    name = "Marion", city = "Prag", label = "person"
                });

                await client.CreateDocumentAsync(personCol.SelfLink, new Person()
                {
                    name = "Maxime", city = "Prag", label = "person"
                });

                await client.CreateDocumentAsync(personCol.SelfLink, new Person()
                {
                    name = "Nina", city = "Munich", label = "person"
                });

                await client.CreateDocumentAsync(personCol.SelfLink, new Person()
                {
                    name = "Maria", city = "Munich", label = "person"
                });

                Console.WriteLine("Done");

                // Demonstrate how to read the Change Feed manually
                // Uncommented for easier repo
                // await ProcessChangeFeedManualy(client, personCol);

                // Demonstrate the use of the ChangeFeed Processor
                await ProcessChangeFeedWithChangeFeedProcessor(client, db, personCol);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Change Feed Demo failed with {ex.Message}.");
                throw;
            }
        }