private static void CreateDatabase(DocumentClient documentClient) { //create a document collection if it doesn't exist. try { documentClient.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseName)).GetAwaiter().GetResult(); } catch (DocumentClientException de) { // If the database does not exist, create it if (de.StatusCode == HttpStatusCode.NotFound) { documentClient.CreateDatabaseAsync(new Database { Id = DatabaseName }).GetAwaiter().GetResult(); } else { throw; } } }
private async Task<DocumentClient> GetDocumentDbClient() { var client = new DocumentClient(new Uri(_endPointUrl), _authorizationKKry); var database = client.CreateDatabaseQuery(). Where(db => db.Id == DocumentDbId).AsEnumerable().FirstOrDefault(); if (database == null) { database = await client.CreateDatabaseAsync( new Database { Id = DocumentDbId }); } DocumentCollection = client.CreateDocumentCollectionQuery ("dbs/" + database.Id).Where(c => c.Id == _collectionId).AsEnumerable().FirstOrDefault(); if (DocumentCollection == null) { DocumentCollection = await client.CreateDocumentCollectionAsync("dbs/" + DocumentDbId, new DocumentCollection { Id = _collectionId }); } return client; }
private static Database GetOrCreateDatabase(DocumentClient client, string databaseName) { // Try to retrieve the database (Microsoft.Azure.Documents.Database) whose Id is equal to databaseName var database = client.CreateDatabaseQuery().Where(db => db.Id == databaseName).ToArray().FirstOrDefault() ?? client.CreateDatabaseAsync(new Database { Id = databaseName }).Result; return database; }
public DocumentClient Initialise() { var configuration = (Configuration)ConfigurationManager.GetSection("DocumentDbProvider"); _documentClient = new DocumentClient(new Uri(configuration.Endpoint), configuration.Key); Database = _documentClient.CreateDatabaseQuery() .Where(d => d.Id == _databaseName).AsEnumerable().FirstOrDefault() ?? _documentClient.CreateDatabaseAsync(new Database { Id = _databaseName }).Result; return _documentClient; }
internal static Database ReadOrCreateDatabase(DocumentClient client, string databaseId) { var databases = client.CreateDatabaseQuery() .Where(db => db.Id == databaseId).ToArray(); if (databases.Any()) { return databases.First(); } var database = new Database { Id = databaseId }; return client.CreateDatabaseAsync(database).Result; }
private static Database GetDatabase(Microsoft.Azure.Documents.Client.DocumentClient client) { // Check to verify a database with the id=LoggingDocumentsDB does not exist var database = client.CreateDatabaseQuery().Where(db => db.Id == "LoggingDocumentsDB").AsEnumerable().FirstOrDefault(); if (database == null) { database = client.CreateDatabaseAsync(new Database { Id = "LoggingDocumentsDB" }).Result; } return(database); }
public static Database GetOrCreateDatabase(DocumentClient client, string databaseId) { IQueryable<Database> dbQuery = from db in client.CreateDatabaseQuery() where db.Id == databaseId select db; IEnumerable<Database> enumerable = dbQuery.AsEnumerable(); if (!enumerable.Any()) { return client.CreateDatabaseAsync(new Database() { Id = databaseId }).Result.Resource; } else { return enumerable.First<Database>(); } }
public async Task<bool> WriteDocument(MessageType type, String jsonString) { var client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["DocumentServiceEndpoint"]), ConfigurationManager.AppSettings["DocumentKey"]); var dbName = ConfigurationManager.AppSettings["DocumentDatabase"]; var database = client.CreateDatabaseQuery().Where(db => db.Id == dbName).AsEnumerable().FirstOrDefault() ?? await client.CreateDatabaseAsync(new Database{ Id = dbName}); // Check to verify a document collection with the does not exist var docCollection = ConfigurationManager.AppSettings["DocumentCollection"]; var documentCollection = client.CreateDocumentCollectionQuery(database.CollectionsLink).Where(c => c.Id == docCollection).AsEnumerable().FirstOrDefault() ?? await client.CreateDocumentCollectionAsync(database.CollectionsLink, new DocumentCollection { Id = docCollection }); var id = Guid.NewGuid().ToString(); var response = HttpStatusCode.Unused; switch (type) { case MessageType.Energy: var energyDoc = JsonConvert.DeserializeObject<EnergyDocument>(jsonString); energyDoc.id = id; response = (await client.CreateDocumentAsync(documentCollection.DocumentsLink, energyDoc)).StatusCode; break; case MessageType.Humidity: var humidityDoc = JsonConvert.DeserializeObject<HumidityDocument>(jsonString); humidityDoc.id = id; response = (await client.CreateDocumentAsync(documentCollection.DocumentsLink, humidityDoc)).StatusCode; break; case MessageType.Light: var lightDoc = JsonConvert.DeserializeObject<LightDocument>(jsonString); lightDoc.id = id; response = (await client.CreateDocumentAsync(documentCollection.DocumentsLink, lightDoc)).StatusCode; break; case MessageType.Temperature: var tempDoc = JsonConvert.DeserializeObject<TemperatureDocument>(jsonString); tempDoc.id = id; response = (await client.CreateDocumentAsync(documentCollection.DocumentsLink, tempDoc)).StatusCode; break; } return response == HttpStatusCode.Created; }
public static async Task SaveTestResults(PerformanceTestResult testResults) { // Make sure to call client.Dispose() once you've finished all DocumentDB interactions // Create a new instance of the DocumentClient var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey); // Check to verify a database with the id=FamilyRegistry does not exist Database database = client.CreateDatabaseQuery().Where(db => db.Id == "DistributedWebTest").AsEnumerable().FirstOrDefault(); if (database == null) { // Create a database database = await client.CreateDatabaseAsync( new Database { Id = "DistributedWebTest" }); } // Check to verify a document collection with the id=FamilyCollection does not exist DocumentCollection documentCollection = client.CreateDocumentCollectionQuery(database.CollectionsLink).Where(c => c.Id == "DistributedTestResults").AsEnumerable().FirstOrDefault(); if (documentCollection == null) { // Create a document collection using the lowest performance tier available (currently, S1) documentCollection = await client.CreateDocumentCollectionAsync(database.CollectionsLink, new DocumentCollection { Id = "DistributedTestResults" }, new RequestOptions { OfferType = "S1" }); } await client.CreateDocumentAsync(documentCollection.DocumentsLink, testResults); }
void Initialize(EventStorageConfiguration configuration) { _client = new DocumentClient(new Uri(configuration.Url), configuration.AuthorizationKey); _client.ReadDatabaseFeedAsync() .ContinueWith(a => _database = a.Result.Where(d => d.Id == configuration.DatabaseId).SingleOrDefault()) .Wait(); if (_database == null) { _database = new Database { Id = configuration.DatabaseId }; _client.CreateDatabaseAsync(_database) .ContinueWith(d => _database = d.Result.Resource) .Wait(); } }
public static async Task<HttpStatusCode> CreateDatabase(DocumentClient client) { var database = await client.CreateDatabaseAsync(new Database() { Id = DbName}); var test = database.StatusCode; return test; }
/// <summary> /// Reads or create a database. /// </summary> /// <param name="client">The client.</param> /// <param name="databaseId">The database identifier.</param> public static async Task<Microsoft.Azure.Documents.Database> ReadOrCreateDatabase(DocumentClient client, string databaseId) { // Get the database var db = client.CreateDatabaseQuery().Where(d => d.Id == databaseId).AsEnumerable().FirstOrDefault(); // Return the database or create it if not exists yet return db ?? await client.CreateDatabaseAsync(new Microsoft.Azure.Documents.Database { Id = databaseId }); }
private static async Task<Database> CreateDatabase(DocumentClient documentClient) { Database database = documentClient.CreateDatabaseQuery().Where(c => c.Id == "courseDatabase").AsEnumerable().FirstOrDefault(); if (database == null) { database = await documentClient.CreateDatabaseAsync(new Database() { Id = "courseDatabase" }); } return database; }
private DocumentConnection CreateDocumentDbConnection() { var client = new DocumentClient(new Uri(EndpointUri), AccountKey); // get the database and if it doesn't exist create it Database database = client.CreateDatabaseQuery() .Where(db => db.Id == Database) .AsEnumerable() .FirstOrDefault(); if (database == null) { Log.LogMessage(MessageImportance.Low, "The database {0} does not exist, will create it.", Database); var task = client.CreateDatabaseAsync(new Database { Id = Database }); database = task.Result; } // get the document collection and if it doesn't exist create it DocumentCollection collection = client.CreateDocumentCollectionQuery(database.SelfLink) .Where(c => c.Id == Collection) .AsEnumerable() .FirstOrDefault(); if (collection == null) { Log.LogMessage(MessageImportance.Low, "The collection {0} does not exist, will create it.", Collection); var task = client.CreateDocumentCollectionAsync(database.SelfLink, new DocumentCollection { Id = Collection }); collection = task.Result; } Log.LogMessage(MessageImportance.Normal, "Connected to DocumentDB database {0}, collection {1}.", Database, Collection); return new DocumentConnection(database, client, collection); }
/// <summary> /// Initialize the DocumentDb settings and connections /// </summary> public void InitializeDocumentDb() { this.DocumentDbEndPointUrl = ConfigurationManager.AppSettings["DocumentDbEndPointUrl"]; if (String.IsNullOrWhiteSpace(this.DocumentDbEndPointUrl)) { throw new ArgumentException("A required AppSetting cannot be null or empty", "DocumentDbEndPointUrl"); } this.DocumentDbAuthorizationKey = ConfigurationManager.AppSettings["DocumentDbAuthorizationKey"]; if (String.IsNullOrWhiteSpace(this.DocumentDbAuthorizationKey)) { throw new ArgumentException("A required AppSetting cannot be null or empty", "DocumentDbAuthorizationKey"); } this.DocumentDbDatabase = ConfigurationManager.AppSettings["DocumentDbDatabase"]; if (String.IsNullOrWhiteSpace(this.DocumentDbDatabase)) { throw new ArgumentException("A required AppSetting cannot be null or empty", "DocumentDbDatabase"); } this.DocumentDbCollection = ConfigurationManager.AppSettings["DocumentDbCollection"]; if (String.IsNullOrWhiteSpace(this.DocumentDbCollection)) { throw new ArgumentException("A required AppSetting cannot be null or empty", "DocumentDbCollection"); } // Create a new instance of the DocumentClient documentClient = new DocumentClient(new Uri(this.DocumentDbEndPointUrl), this.DocumentDbAuthorizationKey); // Check to verify if database already exists Database database = documentClient.CreateDatabaseQuery(). Where(db => db.Id == this.DocumentDbDatabase).AsEnumerable().FirstOrDefault(); if (database == null) { Context.Logger.Info("Creating a new DocumentDb database: {0}", this.DocumentDbDatabase); // Create a database var task = documentClient.CreateDatabaseAsync( new Database { Id = this.DocumentDbDatabase }); task.Wait(); database = task.Result; } else { Context.Logger.Info("Found an existing DocumentDb database: {0}", database.Id); } // Check to verify a document collection already exists documentCollection = documentClient.CreateDocumentCollectionQuery(database.CollectionsLink). Where(c => c.Id == this.DocumentDbCollection).AsEnumerable().FirstOrDefault(); if (documentCollection == null) { Context.Logger.Info("Creating a new DocumentDb collection: {0}", this.DocumentDbCollection); // Create a document collection var task = documentClient.CreateDocumentCollectionAsync(database.CollectionsLink, new DocumentCollection { Id = this.DocumentDbCollection, }); task.Wait(); documentCollection = task.Result; } else { Context.Logger.Info("Found an existing DocumentDb collection: {0}", documentCollection.Id); } }
public async void UploadFeedsToDocumentDB() { var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey); Database database = client.CreateDatabaseQuery() .Where(db => db.Id == databaseId) .AsEnumerable() .FirstOrDefault(); if (database==null) { database = await client.CreateDatabaseAsync(new Database { Id = databaseId }); Console.WriteLine("Created Database: id - {0} and selfLink - {1}", database.Id, database.SelfLink); } DocumentCollection collectionBlog = client.CreateDocumentCollectionQuery(database.CollectionsLink) .Where(doccoll => doccoll.Id == collectionIdBlogs) .AsEnumerable() .FirstOrDefault(); if (collectionBlog == null) { collectionBlog = await client.CreateDocumentCollectionAsync(database.SelfLink, new DocumentCollection { Id = collectionIdBlogs }); Console.WriteLine("Created Collection {0}.", collectionBlog); } DocumentCollection collectionPosts = client.CreateDocumentCollectionQuery(database.CollectionsLink) .Where(doccoll => doccoll.Id == collectionIdPost) .AsEnumerable() .FirstOrDefault(); if (collectionPosts == null) { collectionPosts = await client.CreateDocumentCollectionAsync(database.SelfLink, new DocumentCollection { Id = collectionIdPost }); Console.WriteLine("Created Collection {0}.", collectionPosts); } foreach(var f in this.Feeds) { Console.WriteLine(f.Title); foreach (var post in f.Items) { Console.Write("."); try { await client.CreateDocumentAsync(collectionPosts.SelfLink, post); } catch(Exception ex) { Console.WriteLine("X"); } } f.Items.Clear(); await client.CreateDocumentAsync(collectionBlog.SelfLink, f); Console.WriteLine(); } }
private static async Task<Database> GetDatabase(DocumentClient client) { Database database = client.CreateDatabaseQuery().Where(c => c.Id == "SchoolRegistry").AsEnumerable().FirstOrDefault(); if (database == null) { database = await client.CreateDatabaseAsync(new Database() { Id = "SchoolRegistry" }); } return database; }
private static async Task GetStartedDemo() { // Create a new instance of the DocumentClient var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey); // Check to verify a database with the id=FamilyRegistry does not exist Database database = client.CreateDatabaseQuery().Where(db => db.Id == "FamilyRegistry").AsEnumerable().FirstOrDefault(); // If the database does not exist, create a new database if (database == null) { database = await client.CreateDatabaseAsync( new Database { Id = "FamilyRegistry" }); WriteMessage("Created dbs/FamilyRegistry"); } // Check to verify a document collection with the id=FamilyCollection does not exist DocumentCollection documentCollection = client.CreateDocumentCollectionQuery("dbs/" + database.Id).Where(c => c.Id == "FamilyCollection").AsEnumerable().FirstOrDefault(); // If the document collection does not exist, create a new collection if (documentCollection == null) { documentCollection = await client.CreateDocumentCollectionAsync("dbs/" + database.Id, new DocumentCollection { Id = "FamilyCollection" }); WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection"); } // Check to verify a document with the id=AndersenFamily does not exist Document document = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id).Where(d => d.Id == "AndersenFamily").AsEnumerable().FirstOrDefault(); // If the document does not exist, create a new document if (document == null) { // Create the Andersen Family document Family andersonFamily = new Family { Id = "AndersenFamily", LastName = "Andersen", Parents = new Parent[] { new Parent { FirstName = "Thomas" }, new Parent { FirstName = "Mary Kay"} }, Children = new Child[] { new Child { FirstName = "Henriette Thaulow", Gender = "female", Grade = 5, Pets = new Pet[] { new Pet { GivenName = "Fluffy" } } } }, Address = new Address { State = "WA", County = "King", City = "Seattle" }, IsRegistered = true }; // id based routing for the first argument, "dbs/FamilyRegistry/colls/FamilyCollection" await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, andersonFamily); WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection/docs/AndersenFamily"); } // Check to verify a document with the id=AndersenFamily does not exist document = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id).Where(d => d.Id == "WakefieldFamily").AsEnumerable().FirstOrDefault(); if (document == null) { // Create the WakeField document Family wakefieldFamily = new Family { Id = "WakefieldFamily", Parents = new Parent[] { new Parent { FamilyName= "Wakefield", FirstName= "Robin" }, new Parent { FamilyName= "Miller", FirstName= "Ben" } }, Children = new Child[] { new Child { FamilyName= "Merriam", FirstName= "Jesse", Gender= "female", Grade= 8, Pets= new Pet[] { new Pet { GivenName= "Goofy" }, new Pet { GivenName= "Shadow" } } }, new Child { FamilyName= "Miller", FirstName= "Lisa", Gender= "female", Grade= 1 } }, Address = new Address { State = "NY", County = "Manhattan", City = "NY" }, IsRegistered = false }; // id based routing for the first argument, "dbs/FamilyRegistry/colls/FamilyCollection" await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, wakefieldFamily); WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection/docs/WakefieldFamily"); } // Query the documents using DocumentDB SQL for the Andersen family var families = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id, "SELECT * " + "FROM Families f " + "WHERE f.id = \"AndersenFamily\""); foreach (var family in families) { Console.WriteLine("\tRead {0} from SQL", family); } // Query the documents using LINQ for the Andersen family families = from f in client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id) where f.Id == "AndersenFamily" select f; foreach (var family in families) { Console.WriteLine("Read {0} from LINQ", family); } // Query the documents using LINQ lambdas for the Andersen family families = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id) .Where(f => f.Id == "AndersenFamily") .Select(f => f); foreach (var family in families) { Console.WriteLine("\tRead {0} from LINQ query", family); } // Clean up/delete the database and client await client.DeleteDatabaseAsync("dbs/" + database.Id); client.Dispose(); }
private static async Task GetStartedDemo() { // Make sure to call client.Dispose() once you've finished all DocumentDB interactions // Create a new instance of the DocumentClient var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey); // Check to verify a database with the id=FamilyRegistry does not exist Database database = client.CreateDatabaseQuery().Where(db => db.Id == "FamilyRegistry").AsEnumerable().FirstOrDefault(); if (database == null) { // Create a database database = await client.CreateDatabaseAsync( new Database { Id = "FamilyRegistry" }); } else { Warn("database"); } // Check to verify a document collection with the id=FamilyCollection does not exist DocumentCollection documentCollection = client.CreateDocumentCollectionQuery(database.CollectionsLink).Where(c => c.Id == "FamilyCollection").AsEnumerable().FirstOrDefault(); if (documentCollection == null) { // Create a document collection using the lowest performance tier available (currently, S1) documentCollection = await client.CreateDocumentCollectionAsync(database.CollectionsLink, new DocumentCollection { Id = "FamilyCollection" }, new RequestOptions { OfferType = "S1" }); } else { Warn("document collection"); } // Check to verify a document with the id=AndersenFamily does not exist Document document = client.CreateDocumentQuery(documentCollection.DocumentsLink).Where(d => d.Id == "AndersenFamily").AsEnumerable().FirstOrDefault(); if (document == null) { // Create the Andersen Family document Family AndersonFamily = new Family { Id = "AndersenFamily", LastName = "Andersen", Parents = new Parent[] { new Parent { FirstName = "Thomas" }, new Parent { FirstName = "Mary Kay"} }, Children = new Child[] { new Child { FirstName = "Henriette Thaulow", Gender = "female", Grade = 5, Pets = new Pet[] { new Pet { GivenName = "Fluffy" } } } }, Address = new Address { State = "WA", County = "King", City = "Seattle" }, IsRegistered = true }; await client.CreateDocumentAsync(documentCollection.DocumentsLink, AndersonFamily); } else { Warn("document"); } // Check to verify a document with the id=AndersenFamily does not exist document = client.CreateDocumentQuery(documentCollection.DocumentsLink).Where(d => d.Id == "WakefieldFamily").AsEnumerable().FirstOrDefault(); if (document == null) { // Create the WakeField document Family WakefieldFamily = new Family { Id = "WakefieldFamily", Parents = new Parent[] { new Parent { FamilyName= "Wakefield", FirstName= "Robin" }, new Parent { FamilyName= "Miller", FirstName= "Ben" } }, Children = new Child[] { new Child { FamilyName= "Merriam", FirstName= "Jesse", Gender= "female", Grade= 8, Pets= new Pet[] { new Pet { GivenName= "Goofy" }, new Pet { GivenName= "Shadow" } } }, new Child { FamilyName= "Miller", FirstName= "Lisa", Gender= "female", Grade= 1 } }, Address = new Address { State = "NY", County = "Manhattan", City = "NY" }, IsRegistered = false }; await client.CreateDocumentAsync(documentCollection.DocumentsLink, WakefieldFamily); } else { Warn("document"); } // Query the documents using DocumentDB SQL for the Andersen family var families = client.CreateDocumentQuery(documentCollection.DocumentsLink, "SELECT * " + "FROM Families f " + "WHERE f.id = \"AndersenFamily\""); foreach (var family in families) { Console.WriteLine("\tRead {0} from SQL", family); } // Query the documents using LINQ for the Andersen family families = from f in client.CreateDocumentQuery(documentCollection.DocumentsLink) where f.Id == "AndersenFamily" select f; foreach (var family in families) { Console.WriteLine("\tRead {0} from LINQ", family); } // Query the documents using LINQ lambdas for the Andersen family families = client.CreateDocumentQuery(documentCollection.DocumentsLink) .Where(f => f.Id == "AndersenFamily") .Select(f => f); foreach (var family in families) { Console.WriteLine("\tRead {0} from LINQ query", family); } // Query the documents using DocumentSQl with one join var items = client.CreateDocumentQuery<dynamic>(documentCollection.DocumentsLink, "SELECT f.id, c.FirstName AS child " + "FROM Families f " + "JOIN c IN f.Children"); foreach (var item in items.ToList()) { Console.WriteLine(item); } // Query the documents using LINQ with one join items = client.CreateDocumentQuery<Family>(documentCollection.DocumentsLink) .SelectMany(family => family.Children .Select(children => new { family = family.Id, child = children.FirstName })); foreach (var item in items.ToList()) { Console.WriteLine(item); } // Clean up/delete the database and client await client.DeleteDatabaseAsync(database.SelfLink); client.Dispose(); }
private static async Task<ResourceResponse<Database>> CreateDatabase(DocumentClient client, string databaseName) { return await client.CreateDatabaseAsync(new Database { Id = databaseName }); }
private static async Task CreateDatabase() { var client = new DocumentClient(new Uri(url), auth); // Create the database if it does not exist. Database database = client.CreateDatabaseQuery().Where(db => db.Id == "fProj") .AsEnumerable().FirstOrDefault(); if (database == null) { database = await client.CreateDatabaseAsync(new Database { Id = "fProj" }); } else { Console.WriteLine("Your Database existed previously"); } // Create the Document Collection if it does not exist. DocumentCollection col = client.CreateDocumentCollectionQuery (database.CollectionsLink) .Where(c => c.Id == "fpDocs") .AsEnumerable().FirstOrDefault(); if (col == null) { col = await client.CreateDocumentCollectionAsync (database.CollectionsLink, new DocumentCollection { Id = "fpDocs" }, new RequestOptions { OfferType = "S1" }); } else { Console.WriteLine("Yo, you already had that collection"); } // Create the first document Document doc = client.CreateDocumentQuery(col.DocumentsLink) .Where(d => d.Id == "1").AsEnumerable().FirstOrDefault(); if (doc == null) { Restaurant doc1 = new Restaurant { Id = "1", RName = "Duck's Country Bunker", UserId = "user1", FName = "Phil", LName = "McLovin", MenuItems = new MenuItem[] { new MenuItem { Id = "1", ItemName = "Small Fries", Calories = 333, Price = .99M }, new MenuItem { Id = "2", ItemName = "Medium Fries", Calories = 444, Price = 1.99M }, new MenuItem { Id = "3", ItemName = "Large Fries", Calories = 555, Price = 2.99M }, new MenuItem { Id = "4", ItemName = "Small Beer", Calories = 5, Price = .99M }, new MenuItem { Id = "5", ItemName = "Medium Beer", Calories = 10, Price = 2.00M }, new MenuItem { Id = "6", ItemName = "Normal Sized Beer", Calories = 300, Price = 3.00M }, new MenuItem { Id = "7", ItemName = "Coffee", Calories = 50, Price = 1.00M } }, Address = new Address { Id = "1", StreetNumber = "1235 SE Brooklyn St.", City = "Corvallis", State = "Oregon", ZipCode = "99775" } }; await client.CreateDocumentAsync(col.DocumentsLink, doc1); } // Create the second document doc = client.CreateDocumentQuery(col.DocumentsLink) .Where(d => d.Id == "2").AsEnumerable().FirstOrDefault(); if (doc == null) { Restaurant doc2 = new Restaurant { Id = "2", RName = "Obi One", UserId = "user1", FName = "Allen", LName = "Jones", MenuItems = new MenuItem[] { new MenuItem { Id = "1", ItemName = "Cheeseburger", Calories = 75, Price = .99M }, new MenuItem { Id = "2", ItemName = "Hamburger", Calories = 50, Price = 1M }, new MenuItem { Id = "3", ItemName = "Regular Onion Rings", Calories = 100, Price = 1.50M }, new MenuItem { Id = "4", ItemName = "Large Onion Rings", Calories = 300, Price = 2M } }, Address = new Address { Id = "2", StreetNumber = "4949 N Broadway Ave", City = "Eugene", State = "Oregon", ZipCode = "96709" } }; await client.CreateDocumentAsync(col.DocumentsLink, doc2); } doc = client.CreateDocumentQuery(col.DocumentsLink) .Where(d => d.Id == "3").AsEnumerable().FirstOrDefault(); if (doc == null) { Restaurant doc3 = new Restaurant { Id = "3", RName = "Classy Chicken", UserId = "user2", FName = "Ash", LName = "Awesome", MenuItems = new MenuItem[] { new MenuItem { Id = "1", ItemName = "Small Chicken Dinner", Calories = 1111, Price = 11M }, new MenuItem { Id = "2", ItemName = "Medium Chicken Dinner", Calories = 2222, Price = 22M }, new MenuItem { Id = "3", ItemName = "Large Chicken Dinner", Calories = 3333, Price = 33M }, new MenuItem { Id = "4", ItemName = "Freedom Sized Chicken Dinner", Calories = 4444, Price = 44M }, new MenuItem { Id = "5", ItemName = "Small Chicken Wings", Calories = 500, Price = 5M }, new MenuItem { Id = "6", ItemName = "Medium Chicken Wings", Calories = 1000, Price = 7M }, new MenuItem { Id = "7", ItemName = "Large Chicken Wings", Calories = 1500, Price = 10M } }, Address = new Address { Id = "3", StreetNumber = "500 Midtown Ave", City = "Los Angeles", State = "California", ZipCode = "90210" } }; await client.CreateDocumentAsync(col.DocumentsLink, doc3); } doc = client.CreateDocumentQuery(col.DocumentsLink) .Where(d => d.Id == "4").AsEnumerable().FirstOrDefault(); if (doc == null) { Restaurant doc4 = new Restaurant { Id = "4", RName = "Four Stars", UserId = "user2", FName = "Ash", LName = "Awesome", MenuItems = new MenuItem[] { new MenuItem { Id = "1", ItemName = "Pretentious Meal #1", Calories = 1, Price = 100M }, new MenuItem { Id = "2", ItemName = "Pretentious Meal #2", Calories = 2, Price = 100M }, new MenuItem { Id = "3", ItemName = "Pretentious Meal #3", Calories = 3, Price = 300M }, new MenuItem { Id = "4", ItemName = "Small Gerbil Food", Calories = 4, Price = 400M }, new MenuItem { Id = "5", ItemName = "Medium Gerbil Food", Calories = 5, Price = 50M }, new MenuItem { Id = "6", ItemName = "Large Gerbil Food", Calories = 6, Price = 60M } }, Address = new Address { Id = "4", StreetNumber = "3001 SE Belmont St.", City = "Portland", State = "Oregon", ZipCode = "97214" } }; await client.CreateDocumentAsync(col.DocumentsLink, doc4); } var items = client.CreateDocumentQuery(col.DocumentsLink, "SELECT r.id, r.rName FROM Restaurant r"); // Query and check what I have entered is there. foreach(var rest in items) { Console.WriteLine(rest); } // Begin seeding of the collection with users Document user = client.CreateDocumentQuery(col.DocumentsLink).Where(d => d.Id == "user1") .AsEnumerable().FirstOrDefault(); if (user == null) { Users user1 = new Users { Id = "user1", UserName = "******", Password = "******" }; await client.CreateDocumentAsync(col.DocumentsLink, user1); } user = client.CreateDocumentQuery(col.DocumentsLink).Where(d => d.Id == "user2") .AsEnumerable().FirstOrDefault(); if (user == null) { Users user2 = new Users { Id = "user2", UserName = "******", Password = "******" }; await client.CreateDocumentAsync(col.DocumentsLink, user2); } // TODO: Try to query a user assosciated with a restaurant as a separate document. /* */ //await client.DeleteDatabaseAsync(database.SelfLink); // Dispose of the client connection. client.Dispose(); }
private static Database GetOrCreateDatabase(DocumentClient client, string databaseId) { var db = client.CreateDatabaseQuery() .Where(d => d.Id == databaseId) .AsEnumerable() .FirstOrDefault(); if (db == null) { db = client.CreateDatabaseAsync(new Database { Id = databaseId }).Result; } return db; }
private static async Task GetStartedDemo() { // Create a new instance of the DocumentClient var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey); // Check to verify a database with the id=FamilyRegistry does not exist Database database = client.CreateDatabaseQuery().Where(db => db.Id == "FamilyRegistry").AsEnumerable().FirstOrDefault(); // If the database does not exist, create a new database if (database == null) { database = await client.CreateDatabaseAsync( new Database { Id = "FamilyRegistry" }); WriteMessage("Created dbs/FamilyRegistry"); } // Check to verify a document collection with the id=FamilyCollection does not exist DocumentCollection documentCollection = client.CreateDocumentCollectionQuery("dbs/" + database.Id).Where(c => c.Id == "FamilyCollection").AsEnumerable().FirstOrDefault(); // If the document collection does not exist, create a new collection if (documentCollection == null) { documentCollection = await client.CreateDocumentCollectionAsync("dbs/" + database.Id, new DocumentCollection { Id = "FamilyCollection" }); WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection"); } // Check to verify a document with the id=AndersenFamily does not exist Document document = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id).Where(d => d.Id == "AndersenFamily").AsEnumerable().FirstOrDefault(); // If the document does not exist, create a new document if (document == null) { // Create the Andersen Family document Family andersonFamily = new Family { Id = "AndersenFamily", LastName = "Andersen", Parents = new Parent[] { new Parent { FirstName = "Thomas" , SSN = "111-11-1111"}.Seal(), new Parent { FirstName = "Mary Kay", SSN = "222-22-2222"}.Seal() }, Children = new Child[] { new Child { FirstName = "Henriette Thaulow", Gender = "female", Grade = 5, Pets = new Pet[] { new Pet { GivenName = "Fluffy" } } } }, Address = new Address { State = "WA", County = "King", City = "Seattle" }, IsRegistered = true, GeneticCondition = "diabetes" }; Crypteron.CipherObject.Seal(andersonFamily); // or andersonFamily.Seal() // id based routing for the first argument, "dbs/FamilyRegistry/colls/FamilyCollection" await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, andersonFamily); WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection/docs/AndersenFamily"); } // Check to verify a document with the id=AndersenFamily does not exist document = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id).Where(d => d.Id == "WakefieldFamily").AsEnumerable().FirstOrDefault(); if (document == null) { // Create the WakeField document Family wakefieldFamily = new Family { Id = "WakefieldFamily", Parents = new Parent[] { new Parent { FamilyName= "Wakefield", FirstName= "Robin" }, new Parent { FamilyName= "Miller", FirstName= "Ben" } }, Children = new Child[] { new Child { FamilyName= "Merriam", FirstName= "Jesse", Gender= "female", Grade= 8, Pets= new Pet[] { new Pet { GivenName= "Goofy" }, new Pet { GivenName= "Shadow" } } }, new Child { FamilyName= "Miller", FirstName= "Lisa", Gender= "female", Grade= 1 } }, Address = new Address { State = "NY", County = "Manhattan", City = "NY" }, IsRegistered = false, }; Crypteron.CipherObject.Seal(wakefieldFamily); // or wakefieldFamily.Seal() // id based routing for the first argument, "dbs/FamilyRegistry/colls/FamilyCollection" await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, wakefieldFamily); WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection/docs/WakefieldFamily"); } // Query the documents using DocumentDB SQL for the Andersen family var families = client.CreateDocumentQuery<Family>("dbs/" + database.Id + "/colls/" + documentCollection.Id, "SELECT * " + "FROM Families f " + "WHERE f.id = \"AndersenFamily\""); foreach (var family in families) { Console.WriteLine("\tRead {0} from SQL", JsonConvert.SerializeObject(family.Unseal(), Formatting.Indented)); } // Query the documents using LINQ for the Andersen family families = from f in client.CreateDocumentQuery<Family>("dbs/" + database.Id + "/colls/" + documentCollection.Id) where f.Id == "AndersenFamily" select f; foreach (var family in families) { Console.WriteLine("Read {0} from LINQ", JsonConvert.SerializeObject(family.Unseal(), Formatting.Indented)); } // Query the documents using LINQ lambdas for the Andersen family // Need to get results back in original class with Secure attributes // Dynamic JObject is not currently supported families = client.CreateDocumentQuery<Family>("dbs/" + database.Id + "/colls/" + documentCollection.Id) .Where(f => f.Id == "AndersenFamily") .Select(f => f); foreach (var family in families) { Console.WriteLine("\tRead {0} from LINQ query", JsonConvert.SerializeObject(family.Unseal(), Formatting.Indented)); } // Clean up/delete the database and client Console.WriteLine("Done. Press 'd' to delete database prior to exiting"); var choice = Console.ReadKey().KeyChar; if (choice == 'd' || choice == 'D') { Console.WriteLine("\nDeleting database ..."); await client.DeleteDatabaseAsync("dbs/" + database.Id); } client.Dispose(); }
/// <summary> /// Internal Member to Get or Create an Azure DocumentDB /// </summary> /// <param name="client"></param> /// <returns></returns> private async Task<Database> GetOrCreateDatabaseAsync(DocumentClient client) { Database database = client.CreateDatabaseQuery().Where(db => db.Id == this.Container).ToArray().FirstOrDefault(); if (database == null) { database = await client.CreateDatabaseAsync(new Database { Id = this.Container }); Log.Info("AzureDocDbRequestManager.GetOrCreateDatabaseAsync", "Created Document DB {0}", this.Container); } return database; }
public static async Task<Database> GetDB(DocumentClient client) { Database database = client.CreateDatabaseQuery().Where(db => db.Id == "LMSRegistry") .AsEnumerable().FirstOrDefault() ?? await client.CreateDatabaseAsync( new Database { Id = "LMSRegistry" }); Console.WriteLine(database.SelfLink); return database; }